package com.wusuowei.ucenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wusuowei.common.annotation.Log;
import com.wusuowei.common.constant.BusinessTypeEnum;
import com.wusuowei.common.utils.R;
import com.wusuowei.common.utils.RespEnum;
import com.wusuowei.ucenter.mapper.SysDictMapper;
import com.wusuowei.ucenter.model.po.SysDict;
import com.wusuowei.ucenter.model.po.SysMenu;
import com.wusuowei.ucenter.service.ISysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lgy
 */
@Slf4j
//@PreAuthorize("isAuthenticated()")
@RestController
@RequestMapping("auth/menu")
public class SysMenuController {
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysDictMapper sysDictMapper;

    @PreAuthorize("hasAuthority('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public R getInfo(@PathVariable String menuId) {
        return R.ok().setData(menuService.getById(menuId));
    }

    @PreAuthorize("hasAuthority('system:menu:list')")
    @GetMapping
    public R findAll(@RequestParam(defaultValue = "") String name) {
        return R.ok().setData(menuService.findMenus(name));
    }

    @PreAuthorize("hasAuthority('system:menu:list')")
    @GetMapping("/ids")
    public R findAllIds() {
        return R.ok().setData(menuService.list().stream().map(SysMenu::getId).collect(Collectors.toList()));
    }

    @PreAuthorize("hasAuthority('system:menu:add')")
    @Log(title = "菜单管理`", businessType = BusinessTypeEnum.INSERT)
    @PostMapping
    public R add(@RequestBody SysMenu menu) {
        menuService.save(menu);
        return R.ok();
    }

    @PreAuthorize("hasAuthority('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public R edit(@RequestBody SysMenu menu) {
        menuService.updateById(menu);
        return R.ok();
    }

    @PreAuthorize("hasAuthority('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{menuId}")
    public R deleteBatch(@PathVariable Integer menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return R.error(RespEnum.SUBMENU_EXISTS);
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return R.error(RespEnum.MENU_ASSIGNED);
        }
        menuService.removeById(menuId);
        return R.ok();
    }


    @GetMapping("/icons")
    public R getIcons() {
        QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "icon");
        return R.ok().setData(sysDictMapper.selectList(queryWrapper));
    }

}

